package com.remotephone.myapplication

import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.graphics.Bitmap
import android.media.projection.MediaProjectionManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.provider.Settings
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.remotephone.myapplication.ui.theme.MyApplicationTheme

class MainActivity : ComponentActivity() {
    
    private var hasOverlayPermission by mutableStateOf(false)
    private var hasMediaProjectionPermission by mutableStateOf(false)
    private var isOverlayServiceRunning by mutableStateOf(false)
    private var isScreenshotInProgress by mutableStateOf(false)
    
    // 截图服务连接
    private var screenshotService: ScreenshotService? = null
    private var isServiceBound = false
    
    private val serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(className: ComponentName, service: IBinder) {
            val binder = service as ScreenshotService.ScreenshotBinder
            screenshotService = binder.getService()
            isServiceBound = true
        }
        
        override fun onServiceDisconnected(arg0: ComponentName) {
            isServiceBound = false
            screenshotService = null
        }
    }
    
    // 权限申请启动器
    private val overlayPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) {
        checkOverlayPermission()
    }
    
    // MediaProjection权限申请启动器
    private val mediaProjectionLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == RESULT_OK && result.data != null) {
            hasMediaProjectionPermission = true
            // 启动截图服务
            val intent = Intent(this, ScreenshotService::class.java).apply {
                action = ScreenshotService.ACTION_START_PROJECTION
                putExtra(ScreenshotService.EXTRA_RESULT_CODE, result.resultCode)
                putExtra(ScreenshotService.EXTRA_RESULT_DATA, result.data)
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(intent)
            } else {
                startService(intent)
            }
            Toast.makeText(this, "屏幕录制权限已获得", Toast.LENGTH_SHORT).show()
        }
    }
    
    // 虚拟显示专用的MediaProjection权限申请启动器
    private val virtualDisplayLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == RESULT_OK && result.data != null) {
            // 启动虚拟显示截图服务
            val intent = Intent(this, VirtualDisplayScreenshotService::class.java).apply {
                action = VirtualDisplayScreenshotService.ACTION_START_PROJECTION
                putExtra(VirtualDisplayScreenshotService.EXTRA_RESULT_CODE, result.resultCode)
                putExtra(VirtualDisplayScreenshotService.EXTRA_RESULT_DATA, result.data)
            }
            
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(intent)
            } else {
                startService(intent)
            }
            
            Toast.makeText(this, "虚拟显示已创建，3秒后自动截图", Toast.LENGTH_SHORT).show()
            
            // 延迟执行截图，让虚拟显示稳定
            Handler(Looper.getMainLooper()).postDelayed({
                val screenshotIntent = Intent(this, VirtualDisplayScreenshotService::class.java)
                screenshotIntent.action = VirtualDisplayScreenshotService.ACTION_TAKE_SCREENSHOT
                startService(screenshotIntent)
            }, 3000)
        } else {
            isScreenshotInProgress = false
            Toast.makeText(this, "需要屏幕录制权限才能使用虚拟显示截图", Toast.LENGTH_SHORT).show()
        }
    }
    
    // 🎯 分层截图专用的MediaProjection权限申请启动器
    private val layerSeparationLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == RESULT_OK && result.data != null) {
            // 启动分层截图服务
            val intent = Intent(this, LayerSeparationScreenshotService::class.java).apply {
                action = LayerSeparationScreenshotService.ACTION_START_PROJECTION
                putExtra(LayerSeparationScreenshotService.EXTRA_RESULT_CODE, result.resultCode)
                putExtra(LayerSeparationScreenshotService.EXTRA_RESULT_DATA, result.data)
            }
            
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(intent)
            } else {
                startService(intent)
            }
            
            Toast.makeText(this, "🎯 分层截图系统已启动，5秒后执行截图...", Toast.LENGTH_LONG).show()
            
            // 延迟执行截图，让多层显示系统稳定
            Handler(Looper.getMainLooper()).postDelayed({
                val screenshotIntent = Intent(this, LayerSeparationScreenshotService::class.java)
                screenshotIntent.action = LayerSeparationScreenshotService.ACTION_TAKE_SCREENSHOT
                startService(screenshotIntent)
            }, 5000) // 5秒延迟，因为需要更多时间建立多层系统
        } else {
            isScreenshotInProgress = false
            Toast.makeText(this, "需要屏幕录制权限才能使用分层截图", Toast.LENGTH_SHORT).show()
        }
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        checkPermissions()
        setupScreenshotCallback()
        
        setContent {
            MyApplicationTheme {
                MainScreen(
                    hasOverlayPermission = hasOverlayPermission,
                    hasMediaProjectionPermission = hasMediaProjectionPermission,
                    isOverlayServiceRunning = isOverlayServiceRunning,
                    isScreenshotInProgress = isScreenshotInProgress,
                    onRequestOverlayPermission = { requestOverlayPermission() },
                    onRequestScreenshotPermission = { requestScreenshotPermission() },
                    onToggleOverlayService = { toggleOverlayService() },
                    onTakeScreenshot = { takeScreenshot() },
                    onTestPixelCopyScreenshot = { testPixelCopyScreenshot() },
                    onTestAccessibilityScreenshot = { testAccessibilityScreenshot() },
                    onTestRootScreenshot = { testRootScreenshot() },
                    onTestVirtualDisplayScreenshot = { testVirtualDisplayScreenshot() },
                    onTestLayerSeparationScreenshot = { testLayerSeparationScreenshot() },
                    onSwitchOverlayMode = { mode -> switchOverlayMode(mode) }
                )
            }
        }
    }
    
    private fun setupScreenshotCallback() {
        ScreenshotService.setCallback(object : ScreenshotService.ScreenshotCallback {
            override fun onScreenshotTaken(path: String?) {
                runOnUiThread {
                    isScreenshotInProgress = false
                    
                    if (path != null) {
                        // 打开截图查看页面
                        val intent = Intent(this@MainActivity, ScreenshotViewActivity::class.java)
                        intent.putExtra(ScreenshotViewActivity.EXTRA_SCREENSHOT_PATH, path)
                        startActivity(intent)
                    } else {
                        Toast.makeText(this@MainActivity, "截图失败", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        })
    }
    
    private fun saveBitmapToCache(bitmap: Bitmap, prefix: String = ""): String? {
        return try {
            val screenshotsDir = java.io.File(cacheDir, "screenshots")
            if (!screenshotsDir.exists()) {
                screenshotsDir.mkdirs()
            }
            
            val timestamp = System.currentTimeMillis()
            val screenshotFile = java.io.File(screenshotsDir, "${prefix}screenshot_$timestamp.png")
            
            java.io.FileOutputStream(screenshotFile).use { out ->
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
            }
            
            Log.d("MainActivity", "Screenshot saved: ${screenshotFile.absolutePath}")
            screenshotFile.absolutePath
            
        } catch (e: Exception) {
            Log.e("MainActivity", "Error saving screenshot", e)
            null
        }
    }
    
    private fun checkPermissions() {
        checkOverlayPermission()
    }
    
    private fun checkOverlayPermission() {
        hasOverlayPermission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Settings.canDrawOverlays(this)
        } else {
            true
        }
    }
    
    private fun requestOverlayPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val intent = Intent(
                Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                Uri.parse("package:$packageName")
            )
            overlayPermissionLauncher.launch(intent)
        }
    }
    
    private fun requestScreenshotPermission() {
        val mediaProjectionManager = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
        val captureIntent = mediaProjectionManager.createScreenCaptureIntent()
        mediaProjectionLauncher.launch(captureIntent)
    }
    
    private fun toggleOverlayService() {
        if (!hasOverlayPermission) {
            Toast.makeText(this, "请先授予悬浮窗权限", Toast.LENGTH_SHORT).show()
            return
        }
        
        val intent = Intent(this, OverlayService::class.java)
        if (isOverlayServiceRunning) {
            // 停止服务
            stopService(intent)
            isOverlayServiceRunning = false
            Toast.makeText(this, "遮盖层已关闭", Toast.LENGTH_SHORT).show()
        } else {
            // 启动服务
            intent.action = OverlayService.ACTION_SHOW_OVERLAY
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(intent)
            } else {
                startService(intent)
            }
            isOverlayServiceRunning = true
            Toast.makeText(this, "遮盖层已开启（标准模式）", Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun switchOverlayMode(mode: String) {
        if (!hasOverlayPermission) {
            Toast.makeText(this, "请先授予悬浮窗权限", Toast.LENGTH_SHORT).show()
            return
        }
        
        val intent = Intent(this, OverlayService::class.java)
        intent.action = when (mode) {
            "standard" -> OverlayService.ACTION_SET_MODE_STANDARD
            "invisible" -> OverlayService.ACTION_SET_MODE_INVISIBLE_TO_SCREENSHOT
            "system" -> OverlayService.ACTION_SET_MODE_SYSTEM_LAYER
            "secure" -> OverlayService.ACTION_SET_MODE_SECURE
            "surface_excluded" -> OverlayService.ACTION_SET_OVERLAY_MODE.also {
                intent.putExtra(OverlayService.EXTRA_OVERLAY_MODE, 4) // OVERLAY_MODE_SURFACE_EXCLUDED
            }
            else -> OverlayService.ACTION_SET_MODE_STANDARD
        }
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent)
        } else {
            startService(intent)
        }
        
        val modeText = when (mode) {
            "standard" -> "标准模式"
            "invisible" -> "截图隐形模式"
            "system" -> "系统层级模式"
            "secure" -> "安全防截图模式"
            "surface_excluded" -> "🎯Surface排除模式"
            else -> "标准模式"
        }
        
        Toast.makeText(this, "浮窗已切换到: $modeText", Toast.LENGTH_SHORT).show()
    }
    
    private fun takeScreenshot() {
        if (!hasMediaProjectionPermission) {
            Toast.makeText(this, "请先授予屏幕录制权限", Toast.LENGTH_SHORT).show()
            return
        }
        
        isScreenshotInProgress = true
        Toast.makeText(this, "正在截图...", Toast.LENGTH_SHORT).show()
        
        // 通过服务截图
        val intent = Intent(this, ScreenshotService::class.java)
        intent.action = ScreenshotService.ACTION_TAKE_SCREENSHOT
        startService(intent)
    }
    
    private fun testPixelCopyScreenshot() {
        if (!hasMediaProjectionPermission) {
            Toast.makeText(this, "请先授予屏幕录制权限", Toast.LENGTH_SHORT).show()
            return
        }
        
        isScreenshotInProgress = true
        Toast.makeText(this, "测试PixelCopy API（预期会失败并生成说明文件）", Toast.LENGTH_LONG).show()
        
        // 设置PixelCopy回调
        PixelCopyScreenshotService.setCallback(object : PixelCopyScreenshotService.ScreenshotCallback {
            override fun onScreenshotTaken(path: String?) {
                runOnUiThread {
                    isScreenshotInProgress = false
                    
                    if (path != null) {
                        // 成功（不太可能）
                        val intent = Intent(this@MainActivity, ScreenshotViewActivity::class.java)
                        intent.putExtra(ScreenshotViewActivity.EXTRA_SCREENSHOT_PATH, path)
                        startActivity(intent)
                    } else {
                        // 预期的失败，显示说明
                        Toast.makeText(this@MainActivity, 
                            "如预期，PixelCopy无法截取Display，已生成说明文件到screenshots目录", 
                            Toast.LENGTH_LONG).show()
                    }
                }
            }
        })
        
        // 直接启动PixelCopy测试（不需要MediaProjection权限，因为会演示失败）
        val intent = Intent(this, PixelCopyScreenshotService::class.java)
        intent.action = PixelCopyScreenshotService.ACTION_TAKE_SCREENSHOT
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent)
        } else {
            startService(intent)
        }
    }
    
    private fun testAccessibilityScreenshot() {
        isScreenshotInProgress = true
        
        // 检查无障碍服务是否已启用
        if (AccessibilityScreenshotService.isServiceConnected()) {
            Toast.makeText(this, "使用无障碍服务截图中...", Toast.LENGTH_SHORT).show()
            AccessibilityScreenshotService.takeScreenshot(object : AccessibilityScreenshotService.Companion.ScreenshotCallback {
                override fun onSuccess(bitmap: Bitmap) {
                    runOnUiThread {
                        isScreenshotInProgress = false
                        
                        // 保存bitmap到文件
                        val path = saveBitmapToCache(bitmap, "accessibility_")
                        if (path != null) {
                            Toast.makeText(this@MainActivity, "无障碍截图成功！可能绕过了浮窗", Toast.LENGTH_LONG).show()
                            val intent = Intent(this@MainActivity, ScreenshotViewActivity::class.java)
                            intent.putExtra(ScreenshotViewActivity.EXTRA_SCREENSHOT_PATH, path)
                            startActivity(intent)
                        } else {
                            Toast.makeText(this@MainActivity, "无障碍截图保存失败", Toast.LENGTH_LONG).show()
                        }
                    }
                }
                
                override fun onError(message: String) {
                    runOnUiThread {
                        isScreenshotInProgress = false
                        Toast.makeText(this@MainActivity, 
                            "无障碍截图失败: $message", 
                            Toast.LENGTH_LONG).show()
                    }
                }
            })
        } else {
            // 引导用户开启无障碍服务
            Toast.makeText(this, "请在无障碍设置中启用本应用服务", Toast.LENGTH_LONG).show()
            
            // 打开无障碍设置页面
            try {
                startActivity(Intent(android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS))
            } catch (e: Exception) {
                Log.e("MainActivity", "无法打开无障碍设置", e)
            }
            
            isScreenshotInProgress = false
        }
    }
    
    private fun testRootScreenshot() {
        isScreenshotInProgress = true
        Toast.makeText(this, "测试Root权限截图 - 需要设备已Root", Toast.LENGTH_LONG).show()
        
        // 设置Root回调
        RootScreenshotService.setCallback(object : RootScreenshotService.ScreenshotCallback {
            override fun onScreenshotTaken(path: String?) {
                runOnUiThread {
                    isScreenshotInProgress = false
                    
                    if (path != null) {
                        val intent = Intent(this@MainActivity, ScreenshotViewActivity::class.java)
                        intent.putExtra(ScreenshotViewActivity.EXTRA_SCREENSHOT_PATH, path)
                        startActivity(intent)
                    } else {
                        Toast.makeText(this@MainActivity, 
                            "Root权限不可用或截图失败，已生成说明文件", 
                            Toast.LENGTH_LONG).show()
                    }
                }
            }
        })
        
        // 启动Root截图服务
        val intent = Intent(this, RootScreenshotService::class.java)
        intent.action = RootScreenshotService.ACTION_TAKE_SCREENSHOT
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent)
        } else {
            startService(intent)
        }
    }
    
    private fun testVirtualDisplayScreenshot() {
        if (!hasMediaProjectionPermission) {
            Toast.makeText(this, "请先授予屏幕录制权限", Toast.LENGTH_SHORT).show()
            return
        }
        
        isScreenshotInProgress = true
        Toast.makeText(this, "开始虚拟显示截图 - 获取底层像素流", Toast.LENGTH_LONG).show()
        
        // 设置虚拟显示回调
        VirtualDisplayScreenshotService.setCallback(object : VirtualDisplayScreenshotService.ScreenshotCallback {
            override fun onScreenshotTaken(path: String?) {
                runOnUiThread {
                    isScreenshotInProgress = false
                    
                    if (path != null) {
                        Toast.makeText(this@MainActivity, "虚拟显示截图成功！(底层像素流)", Toast.LENGTH_LONG).show()
                        val intent = Intent(this@MainActivity, ScreenshotViewActivity::class.java)
                        intent.putExtra(ScreenshotViewActivity.EXTRA_SCREENSHOT_PATH, path)
                        startActivity(intent)
                    } else {
                        Toast.makeText(this@MainActivity, 
                            "虚拟显示截图失败，查看日志了解原因", 
                            Toast.LENGTH_LONG).show()
                    }
                }
            }
        })
        
        // 重新申请MediaProjection权限用于虚拟显示
        val mediaProjectionManager = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
        val captureIntent = mediaProjectionManager.createScreenCaptureIntent()
        
        virtualDisplayLauncher.launch(captureIntent)
    }
    
    private fun testLayerSeparationScreenshot() {
        if (!hasMediaProjectionPermission) {
            Toast.makeText(this, "请先授予屏幕录制权限", Toast.LENGTH_SHORT).show()
            return
        }
        
        isScreenshotInProgress = true
        Toast.makeText(this, "🎯 启动分层截图 - 终极浮窗排除方案", Toast.LENGTH_LONG).show()
        
        // 设置分层截图回调
        LayerSeparationScreenshotService.setCallback(object : LayerSeparationScreenshotService.ScreenshotCallback {
            override fun onScreenshotTaken(path: String?) {
                runOnUiThread {
                    isScreenshotInProgress = false
                    
                    if (path != null) {
                        Toast.makeText(this@MainActivity, "🎯 分层截图成功！已排除浮窗", Toast.LENGTH_LONG).show()
                        val intent = Intent(this@MainActivity, ScreenshotViewActivity::class.java)
                        intent.putExtra(ScreenshotViewActivity.EXTRA_SCREENSHOT_PATH, path)
                        startActivity(intent)
                    } else {
                        Toast.makeText(this@MainActivity, 
                            "分层截图失败，查看日志了解详情", 
                            Toast.LENGTH_LONG).show()
                    }
                }
            }
        })
        
        // 重新申请MediaProjection权限用于分层截图
        val mediaProjectionManager = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
        val captureIntent = mediaProjectionManager.createScreenCaptureIntent()
        
        layerSeparationLauncher.launch(captureIntent)
    }
    
    override fun onStart() {
        super.onStart()
        // 绑定截图服务
        if (hasMediaProjectionPermission) {
            val intent = Intent(this, ScreenshotService::class.java)
            bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
        }
    }
    
    override fun onStop() {
        super.onStop()
        // 解绑服务
        if (isServiceBound) {
            unbindService(serviceConnection)
            isServiceBound = false
        }
    }
    
    override fun onDestroy() {
        super.onDestroy()
        
        // 停止服务
        if (isOverlayServiceRunning) {
            stopService(Intent(this, OverlayService::class.java))
        }
        
        if (hasMediaProjectionPermission) {
            val intent = Intent(this, ScreenshotService::class.java)
            intent.action = ScreenshotService.ACTION_STOP_PROJECTION
            startService(intent)
        }
        
        // 清理所有回调
        ScreenshotService.setCallback(null)
        PixelCopyScreenshotService.setCallback(null)
        RootScreenshotService.setCallback(null)
        VirtualDisplayScreenshotService.setCallback(null)
        LayerSeparationScreenshotService.setCallback(null)
    }
}

@Composable
fun MainScreen(
    hasOverlayPermission: Boolean,
    hasMediaProjectionPermission: Boolean,
    isOverlayServiceRunning: Boolean,
    isScreenshotInProgress: Boolean,
    onRequestOverlayPermission: () -> Unit,
    onRequestScreenshotPermission: () -> Unit,
    onToggleOverlayService: () -> Unit,
    onTakeScreenshot: () -> Unit,
    onTestPixelCopyScreenshot: () -> Unit,
    onTestAccessibilityScreenshot: () -> Unit,
    onTestRootScreenshot: () -> Unit,
    onTestVirtualDisplayScreenshot: () -> Unit,
    onTestLayerSeparationScreenshot: () -> Unit,
    onSwitchOverlayMode: (String) -> Unit
    ) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState())
            .padding(24.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Top
    ) {
        // 标题
        Text(
            text = "屏幕截图工具",
            fontSize = 28.sp,
            fontWeight = FontWeight.Bold,
            textAlign = TextAlign.Center,
            modifier = Modifier.padding(bottom = 32.dp)
        )
        
        // 权限状态卡片
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = 24.dp),
            colors = CardDefaults.cardColors(containerColor = Color(0xFFF5F5F5))
        ) {
            Column(
                modifier = Modifier.padding(20.dp)
            ) {
                Text(
                    text = "权限状态",
                    fontSize = 20.sp,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.padding(bottom = 16.dp)
                )
                
                PermissionStatusRow(
                    title = "悬浮窗权限",
                    isGranted = hasOverlayPermission,
                    onRequest = onRequestOverlayPermission
                )
                
                Spacer(modifier = Modifier.height(12.dp))
                
                PermissionStatusRow(
                    title = "屏幕录制权限",
                    isGranted = hasMediaProjectionPermission,
                    onRequest = onRequestScreenshotPermission
                )
            }
        }
        
        // 功能控制区域
        Card(
            modifier = Modifier.fillMaxWidth(),
            colors = CardDefaults.cardColors(containerColor = Color(0xFFF5F5F5))
        ) {
            Column(
                modifier = Modifier.padding(20.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text(
                    text = "功能控制",
                    fontSize = 20.sp,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.padding(bottom = 20.dp)
                )
                
                // 遮盖层控制按钮
                Button(
                    onClick = onToggleOverlayService,
                    enabled = hasOverlayPermission,
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(56.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = if (isOverlayServiceRunning) Color.Red else Color.Blue
                    ),
                    shape = RoundedCornerShape(12.dp)
                ) {
                    Text(
                        text = if (isOverlayServiceRunning) "关闭屏幕遮盖" else "开启屏幕遮盖",
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold
                    )
                }
                
                Spacer(modifier = Modifier.height(16.dp))
                
                // 浮窗模式切换区域
                if (isOverlayServiceRunning) {
                    Text(
                        text = "浮窗模式切换",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Bold,
                        modifier = Modifier.padding(bottom = 8.dp)
                    )
                    
                    // 浮窗模式按钮 - 第一行
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(4.dp)
                    ) {
                        Button(
                            onClick = { onSwitchOverlayMode("standard") },
                            modifier = Modifier
                                .weight(1f)
                                .height(40.dp),
                            colors = ButtonDefaults.buttonColors(
                                containerColor = Color(0xFF607D8B)
                            ),
                            shape = RoundedCornerShape(8.dp)
                        ) {
                            Text("标准", fontSize = 11.sp, fontWeight = FontWeight.Bold)
                        }
                        
                        Button(
                            onClick = { onSwitchOverlayMode("invisible") },
                            modifier = Modifier
                                .weight(1f)
                                .height(40.dp),
                            colors = ButtonDefaults.buttonColors(
                                containerColor = Color(0xFF795548)
                            ),
                            shape = RoundedCornerShape(8.dp)
                        ) {
                            Text("隐形", fontSize = 11.sp, fontWeight = FontWeight.Bold)
                        }
                    }
                    
                    Spacer(modifier = Modifier.height(4.dp))
                    
                    // 浮窗模式按钮 - 第二行
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(4.dp)
                    ) {
                        Button(
                            onClick = { onSwitchOverlayMode("system") },
                            modifier = Modifier
                                .weight(1f)
                                .height(40.dp),
                            colors = ButtonDefaults.buttonColors(
                                containerColor = Color(0xFF009688)
                            ),
                            shape = RoundedCornerShape(8.dp)
                        ) {
                            Text("系统层", fontSize = 11.sp, fontWeight = FontWeight.Bold)
                        }
                        
                        Button(
                            onClick = { onSwitchOverlayMode("secure") },
                            modifier = Modifier
                                .weight(1f)
                                .height(40.dp),
                            colors = ButtonDefaults.buttonColors(
                                containerColor = Color(0xFF8BC34A)
                            ),
                            shape = RoundedCornerShape(8.dp)
                        ) {
                            Text("安全", fontSize = 11.sp, fontWeight = FontWeight.Bold)
                        }
                    }
                    
                    Spacer(modifier = Modifier.height(4.dp))
                    
                    // 浮窗模式按钮 - 第三行（高级模式）
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.Center
                    ) {
                        Button(
                            onClick = { onSwitchOverlayMode("surface_excluded") },
                            modifier = Modifier
                                .width(140.dp)
                                .height(40.dp),
                            colors = ButtonDefaults.buttonColors(
                                containerColor = Color(0xFFE91E63)
                            ),
                            shape = RoundedCornerShape(8.dp)
                        ) {
                            Text("🎯Surface排除", fontSize = 11.sp, fontWeight = FontWeight.Bold)
                        }
                    }
                    
                    Spacer(modifier = Modifier.height(16.dp))
                    
                    Text(
                        text = "💡 不同模式使用不同窗口参数，测试哪种能绕过截图",
                        fontSize = 12.sp,
                        color = Color(0xFF666666),
                        textAlign = TextAlign.Center,
                        modifier = Modifier.padding(bottom = 16.dp)
                    )
                }
                
                // 截图按钮组 - 第一行
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    // 常规截图（包含浮窗）
                    Button(
                        onClick = onTakeScreenshot,
                        enabled = hasMediaProjectionPermission && !isScreenshotInProgress,
                        modifier = Modifier
                            .weight(1f)
                            .height(56.dp),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color(0xFF4CAF50)
                        ),
                        shape = RoundedCornerShape(12.dp)
                    ) {
                        if (isScreenshotInProgress) {
                            CircularProgressIndicator(
                                modifier = Modifier.size(16.dp),
                                color = Color.White,
                                strokeWidth = 2.dp
                            )
                        } else {
                            Column(
                                horizontalAlignment = Alignment.CenterHorizontally
                            ) {
                                Text("📸", fontSize = 16.sp)
                                Text("完整截图", fontSize = 12.sp, fontWeight = FontWeight.Bold)
                            }
                        }
                    }
                    
                    // PixelCopy截图（展示API限制）
                    Button(
                        onClick = onTestPixelCopyScreenshot,
                        enabled = hasMediaProjectionPermission && !isScreenshotInProgress,
                        modifier = Modifier
                            .weight(1f)
                            .height(56.dp),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color(0xFF2196F3)
                        ),
                        shape = RoundedCornerShape(12.dp)
                    ) {
                        Column(
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {
                            Text("🧪", fontSize = 16.sp)
                            Text("PixelCopy", fontSize = 12.sp, fontWeight = FontWeight.Bold)
                        }
                    }
                }
                
                Spacer(modifier = Modifier.height(8.dp))
                
                // 截图按钮组 - 第二行（高级方案）
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    // 无障碍截图（Android 11+）
                    Button(
                        onClick = onTestAccessibilityScreenshot,
                        enabled = !isScreenshotInProgress,
                        modifier = Modifier
                            .weight(1f)
                            .height(56.dp),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color(0xFFFF9800)
                        ),
                        shape = RoundedCornerShape(12.dp)
                    ) {
                        Column(
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {
                            Text("♿", fontSize = 16.sp)
                            Text("无障碍", fontSize = 12.sp, fontWeight = FontWeight.Bold)
                        }
                    }
                    
                    // Root权限截图
                    Button(
                        onClick = onTestRootScreenshot,
                        enabled = !isScreenshotInProgress,
                        modifier = Modifier
                            .weight(1f)
                            .height(56.dp),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color(0xFFE91E63)
                        ),
                        shape = RoundedCornerShape(12.dp)
                    ) {
                        Column(
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {
                            Text("🔓", fontSize = 16.sp)
                            Text("Root权限", fontSize = 12.sp, fontWeight = FontWeight.Bold)
                        }
                    }
                }
                
                Spacer(modifier = Modifier.height(8.dp))
                
                // 截图按钮组 - 第三行（虚拟显示）
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    // 虚拟显示截图
                    Button(
                        onClick = onTestVirtualDisplayScreenshot,
                        enabled = hasMediaProjectionPermission && !isScreenshotInProgress,
                        modifier = Modifier
                            .weight(1f)
                            .height(56.dp),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color(0xFF673AB7)
                        ),
                        shape = RoundedCornerShape(12.dp)
                    ) {
                        Column(
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {
                            Text("🖥️", fontSize = 16.sp)
                            Text("虚拟显示", fontSize = 12.sp, fontWeight = FontWeight.Bold)
                        }
                    }
                    
                    // 🎯 分层截图（终极方案）
                    Button(
                        onClick = onTestLayerSeparationScreenshot,
                        enabled = hasMediaProjectionPermission && !isScreenshotInProgress,
                        modifier = Modifier
                            .weight(1f)
                            .height(56.dp),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color(0xFF9C27B0)
                        ),
                        shape = RoundedCornerShape(12.dp)
                    ) {
                        Column(
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {
                            Text("🎯", fontSize = 16.sp)
                            Text("分层截图", fontSize = 12.sp, fontWeight = FontWeight.Bold)
                        }
                    }
                }
                
                Spacer(modifier = Modifier.height(8.dp))
                
                // 手动截图提示按钮
                Button(
                    onClick = { /* TODO: 显示截图指导 */ },
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(48.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color(0xFF9C27B0)
                    ),
                    shape = RoundedCornerShape(12.dp)
                ) {
                    Text(
                        text = "💡 手动截图指导",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Bold
                    )
                }
            }
        }
        
        // 使用说明
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 24.dp),
            colors = CardDefaults.cardColors(containerColor = Color(0xFFFFF3E0))
        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                Text(
                    text = "📋 使用说明",
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.padding(bottom = 8.dp)
                )
                Text(
                    text = "1. 首先授予悬浮窗权限和屏幕录制权限\n" +
                          "2. 开启屏幕遮盖后，屏幕上半部分会显示黑色遮盖层\n" +
                          "3. 浮窗模式切换（仅在遮盖层开启时显示）：\n" +
                          "   • 标准：常规应用层浮窗\n" +
                          "   • 隐形：添加FLAG_SECURE防截图标志\n" +
                          "   • 系统层：尝试使用系统级窗口类型\n" +
                          "   • 安全：组合多种防截图标志\n" +
                          "4. 绕过浮窗的高级截图方案：\n" +
                          "   • 完整截图：包含遮盖层的MediaProjection截图\n" +
                          "   • PixelCopy：演示API限制（教育用途）\n" +
                          "   • 无障碍：Android 11+支持，需启用无障碍服务\n" +
                          "   • Root权限：直接访问系统底层，需要Root设备\n" +
                          "   • 虚拟显示：理论可行但实际仍会包含浮窗\n" +
                          "   • 🎯 分层截图：终极方案，多重技术融合\n" +
                          "   • 手动截图：使用系统快捷键（最可靠）\n" +
                          "5. 技术现实：大多数方案无法真正绕过浮窗\n" +
                          "6. 推荐：使用系统截图快捷键或临时隐藏浮窗",
                    fontSize = 14.sp,
                    lineHeight = 20.sp,
                    color = Color(0xFF666666)
                )
            }
        }
        
        // 底部间距，确保滚动体验
        Spacer(modifier = Modifier.height(32.dp))
    }
}

@Composable
fun PermissionStatusRow(
    title: String,
    isGranted: Boolean,
    onRequest: () -> Unit
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = title,
            fontSize = 16.sp,
            modifier = Modifier.weight(1f)
        )
        
        if (isGranted) {
            Text(
                text = "✅ 已授权",
                color = Color(0xFF4CAF50),
                fontWeight = FontWeight.Bold
            )
        } else {
            Button(
                onClick = onRequest,
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color(0xFFFF9800)
                ),
                shape = RoundedCornerShape(8.dp)
            ) {
                Text("授权", color = Color.White, fontWeight = FontWeight.Bold)
            }
        }
    }
}